package com.globallogic.training.javase.basics;

import java.util.Scanner;
import java.util.Arrays;

/**
* This program returns all the prime numbers
* which are smaller or equal to the inputted from keyboard integer number.
* @version 1.2 2013-04-05
* @author Ivan Moisiienko
*/

public class PrimeNumbers {

	static final String PROMPT_MESSAGE = "Enter any positive number: ";
	static final String PRIMES_OUTPUT_MESSAGE
		= "The list of prime numbers for %d is %s";
	static final String NO_PRIMES_OUTPUT_MESSAGE
		= "There are no prime numbers for number %d.";

	public static void main(String[] args) {

		int inputNumber = provideInput();
		int[] primeNumbers = new int[countPrimeNumbers(inputNumber)];
		int primeNumbersIndex = 0;

		for (int i = 2; i <= inputNumber; i++) {
			if (isPrime(i)) {
				primeNumbers[primeNumbersIndex] = i;
				primeNumbersIndex++;
			}
		}

		printResult(inputNumber, primeNumbers);

	}

	static int provideInput() {

		Scanner in = new Scanner(System.in);
		int result;

		do {
			System.out.print(PROMPT_MESSAGE);
			result = in.nextInt();
		} while (result < 1);

		return result;
	}

	static int countPrimeNumbers(int n) {
		int result = 0;

		for (int i = 2; i <= n; i++) {
			if (isPrime(i)) {
				result += 1;
			}
		}
		return result;
	}

	static boolean isPrime(int n) {

        for (int i = 2; i <= (int) Math.sqrt(n); i++) {
            if (n % i == 0) {
            	return false;
            }
        }
        return true;
	}

	static void printResult(int number, int[] primeNumbers) {
		if (primeNumbers.length > 0) {
			System.out.printf(PRIMES_OUTPUT_MESSAGE,
							  number, Arrays.toString(primeNumbers));
		} else {
			System.out.printf(NO_PRIMES_OUTPUT_MESSAGE, number);
		}
	}

}